## package signup

## private

$form_valid =
  username: false
  id: false
  email: false
  password: false
  confirm: false

#TODO: Combine these
$email_regex = /\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i
$school_nz_regex = /\.school\.nz$/

set_valid = (id, valid) ->
  $form_valid[id] = valid
  if valid
    $("##{id}-wrapper").removeClass 'error'
    $("##{id}-error").hide()
  else
    $("##{id}-wrapper").addClass 'error'
    $("##{id}-error").fadeIn()
    
validate_email = (text) ->
  $email_regex.test(text) and $school_nz_regex.test(text)

validate_password = (text) ->
  text.length >= 8

## initialize

$ ->
  # Validation
  $('#username-box').change ->
    set_valid 'username', ($('#username-box').val() isnt "")
  $('#id-box').change ->
    unless $('#id-box').val().length is 3
      set_valid 'id', no
      return
    $.post '/school/id/check', { i: $('#id-box').val() }, (data) ->
      set_valid 'id', !data.error
  $('#email-box').change ->
    set_valid 'email', validate_email($('#email-box').val())
  $('#password-box').change ->
    set_valid 'password', validate_password($('#password-box').val())
  $('#password-confirm').change ->
    set_valid 'confirm', ($('#password-confirm').val() is $('#password-box').val())
  # Submit
  $('#submit-btn').click ->
    if _.contains($form_valid, false)
      $.meow { message: "You can't sign up until you've completed the form." }
      return
    params = { u: $('#username-box').val(), i: $('#id-box').val(), e: $('#email-box').val(), p: hash($('#password-box').val()) }
    $.post '/signup/school/validate', params, (data) ->
      if data.error
        $.meow { message: "The server doesn't like your values ... Check the form is valid, and if it is then <a target='_blank' href='/contact'>contact us!</a>" }
      else
        $('#main').fadeOut()
        $('#validate').fadeIn()
